package com.util;

import cn.hutool.core.bean.BeanUtil;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则工具
 */
public class RegexpUitl {
    public static String PATTERN = "(<!\\[CDATA\\[)(.*)(]]>)";

    /**
     * 单个字符串
     * @param string
     * @return
     */
    public static String Cdata(String string){
        if(StringUtils.isEmpty(string)){
            return string;
        }
        Pattern compile = Pattern.compile(PATTERN);
        Matcher matcher = compile.matcher(string);
        if(matcher.find()){
            return matcher.group(2);
        }
        else{
            return string;
        }
    }

    /**
     * 替换
     * @param string
     * @return
     */
    public static String CdataReplace(String string){
        String one = CdataReplace(string,"CDATA","");
        String two = CdataReplace(one,"\\<\\!\\[\\[","");
        String three = CdataReplace(two,"]]>","");
        String four = CdataReplace(three,"\\r","");
        String five = CdataReplace(four,"\\n","<br/>");

        return five;
    }

    /**
     * 替换
     * @param string
     * @return
     */
    public static String CdataReplace(String string,String pattern,String replace){
        if(StringUtils.isEmpty(string)){
            return string;
        }
        Pattern compile = Pattern.compile(pattern);
        Matcher matcher = compile.matcher(string);
        StringBuffer buffer = new StringBuffer();
        while (matcher.find()){
           matcher.appendReplacement(buffer,replace);
        }
       matcher.appendTail(buffer);
        if(StringUtils.isEmpty(buffer.toString())){
            return string;
        }
        return buffer.toString();
    }

    /**
     * 单个对象转换
     * @param t
     * @param <T>
     * @return
     */
    public  static <T> T CdataObject(T t){
        Map<String, Object> map = BeanUtil.beanToMap(t);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            //不是字符串就跳过
           if(entry.getValue()==null || !entry.getValue().getClass().equals(String.class)){
               continue;
           }
            String str = RegexpUitl.Cdata((String) entry.getValue());
           map.put(entry.getKey(),str);
        }
       return (T)BeanUtil.mapToBean(map,t.getClass(),true);

    }

}
